/*!
 * blogedit.html 页面脚本.
 * 
 * @since: 1.0.0 2017-03-26
 * @author Way Lau <https://waylau.com>
 */
"use strict";
//# sourceURL=blogedit.js

// DOM 加载完再执行
$(function() {
 
	// 初始化 md 编辑器
    $("#md").markdown({
        language: 'zh',
        fullscreen: {
            enable: true
        },
        resize:'vertical',
        localStorage:'md',
        imgurl: 'http://localhost:8090',
        base64url: 'http://localhost:8090'
    });
 

    
    // 初始化下拉
    $('.form-control-chosen').chosen();
    
    
    // 初始化标签
    $('.form-control-tag').tagsInput({
    	'defaultText':'输入标签'
 
    });

    var curImgBase64;
    var curImgFileName;
    var uploadImg = [];

    // 抓取上传图片，转换代码结果，显示图片的dom
    var img_upload=document.getElementById("file");
    var readFile = function(){

        console.log("read file");

        var file=this.files[0];
        if(!/image\/\w+/.test(file.type)){
            alert("请确保文件为图像类型");
            return false;
        }
        var reader=new FileReader();
        reader.readAsDataURL(file);
        reader.onload=function(){
            curImgBase64 = this.result;
            curImgFileName = $("#file").val().substring($("#file").val().lastIndexOf("\\")+1);
            console.log(curImgFileName);
        }
    };
    // 添加功能出发监听事件
    img_upload.addEventListener('change',readFile,false);

    $("#uploadImage").click(function() {

        $.ajax({
            url: 'http://localhost:8090/img/save',
            type: 'POST',
            cache: false,
            data:{base64:curImgBase64},
            dataType : "json",
            success: function(data){
                uploadImg.push({
                    "imgName":curImgFileName,
                    "imgId":data.id
                });
                var mdcontent=$("#md").val();
                $("#md").val(mdcontent + "\n![]("+curImgFileName +") \n");
            }
        }).done(function(res) {
            $('#file').val('');
        }).fail(function(res) {});
    });

 
 	// 发布博客
 	$("#submitBlog").click(function() {
 		
		// 获取 CSRF Token 
		var csrfToken = $("meta[name='_csrf']").attr("content");
		var csrfHeader = $("meta[name='_csrf_header']").attr("content");

		$.ajax({
		    url: '/u/'+ $(this).attr("userName") + '/blogs/edit',
		    type: 'POST',
			contentType: "application/json; charset=utf-8",
		    data:JSON.stringify({"id":$('#blogId').val(), 
		    	"title": $('#title').val(), 
		    	"summary": $('#summary').val() , 
		    	"content": $('#md').val(),
                "catalogId":$('#catalogSelect').val(),
                "genreId":$('#genreSelect').val(),
		    	"tags":$('.form-control-tag').val(),
                "imgs":uploadImg,
                "type":$("#type").val()
		    	}),
			beforeSend: function(request) {
			    request.setRequestHeader(csrfHeader, csrfToken); // 添加  CSRF Token 
			},
			 success: function(data){
				 if (data.success) {
					// 成功后，重定向
					 window.location = data.body;
				 } else {
					 toastr.error("error!"+data.message);
				 }
		     },
		     error : function() {
		    	 toastr.error("error!");
		     }
		})
 	})
 	
 	
});